package com.jzqf.harmonydemo.utils;

import io.reactivex.rxjava3.core.Observable;
import ohos.app.Context;
import ohos.bundle.IBundleManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 动态权限申请
 *
 * @author LiuWeiHao
 * 2021/5/21 14:00
 */
public class PermissionUtil {
    private static final int PERMISSION_REQUEST_CODE = 101;

    public static Observable<Boolean> request(Context context, String... permissions) {
        List<String> permissionRequest = new ArrayList<>();
        for (String permission : permissions) {
            //校验是否未已授权,校验是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
            if (context.verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED
                    && context.canRequestPermission(permission)) {
                permissionRequest.add(permission);
            }
        }
        if (permissionRequest.size() == 0) {
            return Observable.just(true);
        }
        //申请弹窗授权
        context.requestPermissionsFromUser(permissionRequest.toArray(new String[permissionRequest.size()]),
                PERMISSION_REQUEST_CODE);

        return Observable.just(false);
    }

    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                // 权限被授予
                // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
            } else {
                // 权限被拒绝
            }
        }
    }
}
